package flc.ast.activity;

import static com.stark.imgocr.api.VerifyMethod.APPCODE;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.imgocr.ImgOcrEntry;
import com.stark.imgocr.api.Config;
import com.stark.imgocr.api.IRetCallback;
import com.stark.imgocr.api.bean.OcrRetBean;

import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityPhotoRecBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkFlashUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class PhotoRecActivity extends BaseAc<ActivityPhotoRecBinding> {


    @Override
    protected int onCreate() {
        return R.layout.activity_photo_rec;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPhotoRecBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivFlash.setOnClickListener(this);
        mDataBinding.ivReversal.setOnClickListener(this);
        mDataBinding.ivTakePhoto.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivFlash://闪光灯
                openFlash();
                break;
            case R.id.ivReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivTakePhoto://拍照
                mDataBinding.cameraView.takePictureSnapshot();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_photo_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        applyCropImage(bitmap);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    public void applyCropImage(Bitmap bitmap) {
        showDialog(getString(com.stark.common.res.R.string.handling));
        Config config;
        config = Config.verifyByAppCode(String.valueOf(APPCODE));
        ImgOcrEntry.init(config);
        ImgOcrEntry.getOcrReqManager().urlImages(PhotoRecActivity.this, bitmap, new IRetCallback<List<OcrRetBean.Word>>() {
            @Override
            public void onRet(String errCode, String errMsg, @Nullable List<OcrRetBean.Word> wordList) {
                if (isDestroyed()) {
                    return;
                }
                if (wordList == null) {
                    ToastUtils.showShort(errMsg);
                    return;
                }
                StringBuilder stringBuilder = new StringBuilder();
                OcrRetBean.Word word = null;
                for (int i = 0; i < wordList.size(); i++) {
                    word = wordList.get(i);
                    stringBuilder.append(word.getWords());
                    if (i != wordList.size() - 1) {
                        stringBuilder.append("\n");
                    }
                }
                dismissDialog();
                RecResultActivity.sResult = stringBuilder.toString();
                startActivity(RecResultActivity.class);
            }
        });
    }


    //打开/关闭闪光灯
    private void openFlash() {
        if (StkFlashUtil.isFlashlightEnable()) {
            StkFlashUtil.setFlashlightStatus(false);
            mDataBinding.ivFlash.setImageResource(R.drawable.asgdgb);
        } else {
            StkFlashUtil.setFlashlightStatus(true);
            mDataBinding.ivFlash.setImageResource(R.drawable.asgddk);
        }
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

}